type callbackType = (...args: any) => void
class UseWebsocket {
    private socket =
        new WebSocket(`ws://${location.hostname}:8080`);
    private from = "user";
    private to = "server";

    private handler: {
        [key: string]: callbackType
    } = {}

    constructor() {
        this.socket.addEventListener("message", (e) => {
            const data = JSON.parse(e.data);
            console.log(data.msg, data);
            if (data.handleKey) {
                this.handler[data.handleKey](data)
            }
        });
    }
    public send(msg: string, callback: callbackType) {
        const key = new Date().valueOf()
        this.handler[key] = callback
        this.socket.send(
            JSON.stringify({
                from: this.from,
                to: this.to,
                handleKey: key,
                msg,
            })
        );
    }

    public sendObj(key: string, data: string, callback: callbackType = () => { }) {
        this.send(key + "|" + data, callback)
    }

    public disconnect() {
        this.socket.close()
    }
}

export const ws = new UseWebsocket()